package com.study.talk.data.repository

import android.util.Log
import androidx.lifecycle.LiveData
import com.study.common.DateUtil
import com.study.common.annotation.Desc
import com.study.talk.data.local.ChatCacheDao
import com.study.talk.data.local.GroupMessageDao
import com.study.talk.data.local.MessageDao
import com.study.talk.data.model.ChatCache
import com.study.talk.data.model.GroupInfo
import com.study.talk.data.model.GroupMessageRecord
import com.study.talk.data.model.Message
import com.study.talk.data.model.MessageRecord
import com.study.talk.data.model.UserInfo
import com.study.talk.data.remote.MsgApi
import com.study.talk.netty.message.response.AddUserResponse
import com.study.talk.netty.message.response.GroupMessageSelfResponse
import com.study.talk.netty.message.response.MessageSelfResponse
import javax.inject.Inject

class MsgRepository @Inject constructor(
    private val messageDao: MessageDao,
    private val groupMessageDao: GroupMessageDao,
    private val cacheDao: ChatCacheDao,
    private val userRepository: UserRepository,
    private val groupRepository: GroupRepository,
    private val msgApi: MsgApi
) : BaseRepository() {

    companion object {
        private const val TAG = "MsgRepository"
    }

    @Desc("获取聊天信息列表(好友)")
    fun getMessages(chatId: Int): LiveData<List<MessageRecord>> {
        return messageDao.query(chatId)
    }

    @Desc("获取聊天信息列表(群聊)")
    fun getGroupMsg(groupId: Int): LiveData<List<GroupMessageRecord>> {
        return groupMessageDao.query(groupId)
    }

    @Desc("添加聊天消息")
    fun addMsg(msg: MessageRecord) {
        messageDao.insert(msg)
        updateCache(ChatCache().apply {
            name = msg.username
            avatar = msg.avatar
            chatType = 1
            lastContent = if (msg.messageType == 1) "[图片]" else msg.content
            status = true
            userId = msg.userId
            groupId = null
            createTime = DateUtil.currentTime()
        })
    }

    @Desc("添加群聊天信息")
    suspend fun addMsg(
        msg: GroupMessageRecord, success: (GroupInfo) -> Unit = {}, fail: (String) -> Unit = {}
    ) {
        groupMessageDao.insert(msg) //新增消息
        groupRepository.getGroupInfo(msg.groupId, success = { group ->
            //更新缓存
            updateGroupCache(ChatCache().apply {
                name = group.name
                avatar = group.avatar
                chatType = 2
                lastContent = if (msg.messageType == 1) "[图片]" else msg.content
                status = true
                userId = null
                groupId = group.id
                createTime = DateUtil.currentTime()
            })
            success(group)
        }, fail = fail)
    }

    @Desc("添加聊天消息")
    suspend fun addMsg(response: MessageSelfResponse, user: UserInfo) {
        //新增消息
        messageDao.insert(
            MessageRecord(
                user,
                response,
                response.receiverId
            )
        )
        val friend = userRepository.getUserInfo(response.receiverId)
        if (friend == null) {
            Log.e(TAG, "addMsg: fail,friendInfo is null")
        } else {
            updateCache(ChatCache().apply {
                name = friend.username
                avatar = friend.avatar
                userId = friend.id
                groupId = null
                chatType = 1
                status = true
                lastContent = if (response.messageType == 1) "[图片]" else response.content
                createTime = DateUtil.currentTime()
            })
        }
    }


    @Desc("添加群聊天消息")
    suspend fun addMsg(response: GroupMessageSelfResponse, user: UserInfo) {
        addMsg(
            GroupMessageRecord(
                user,
                response,
                true
            )
        )
    }

    @Desc("更新聊天缓存列表")
    private fun updateCache(cache: ChatCache) {
        if (cacheDao.hasUser(cache.userId)) {
            cache.id = cacheDao.queryUser(cache.userId).id
            cacheDao.update(cache)
        } else {
            cacheDao.insert(cache)
        }
    }

    @Desc("更新群聊天缓存列表")
    private fun updateGroupCache(cache: ChatCache) {
        if (cacheDao.hasGroup(cache.groupId)) {
            cache.id = cacheDao.queryGroup(cache.groupId).id
            cacheDao.update(cache)
        } else {
            cacheDao.insert(cache)
        }
    }

    @Desc("获取缓存列表")
    fun getCaches(): LiveData<MutableList<ChatCache>> {
        return cacheDao.query()
    }

    @Desc("获取所有群聊的")
    suspend fun getAllMsg(): List<Message> {
        val response = msgApi.getAllMsg()
        if (response.isSuccessful) {
            if (response.body()?.status == 200) {
                return if (response.body()?.data.isNullOrEmpty()) {
                    listOf()
                } else {
                    response.body()?.data!!
                }
            } else {
                Log.e(TAG, "getAllMsg: error,msg:${response.body()?.message}")
                return listOf()
            }
        } else {
            Log.e(TAG, "getAllMsg: fail,msg:${response.message()}")
            return listOf()
        }
    }

    @Desc("获取服务器中未读的消息")
    suspend fun getServerCacheMsg(userId: Int): List<Message> {
        val response = msgApi.getCacheMsg(userId)
        if (response.isSuccessful) {
            if (response.body()?.status == 200) {
                return if (response.body()?.data.isNullOrEmpty()) {
                    listOf()
                } else {
                    response.body()?.data!!
                }
            } else {
                Log.e(TAG, "getServerCacheMsg: error,msg:${response.body()?.message}")
                return listOf()
            }
        } else {
            Log.e(TAG, "getServerCacheMsg: fail,msg:${response.message()}")
            return listOf()
        }
    }

    @Desc("查询是否存在缓存")
    fun addCache(response: AddUserResponse) {
        if (!cacheDao.hasUser(response.inviteId)) { //之前未添加过好友 没有聊天缓存
            cacheDao.insert(ChatCache().apply {
                name = response.inviteName
                avatar = response.inviteAvatar
                chatType = 1
                lastContent = ""
                status = true
                userId = response.inviteId
                groupId = null
                createTime = DateUtil.currentTime()
            })
        }
    }
}